/**
 * Project Name:springmvc
 * File Name:NettyServerHandler.java
 * Package Name:com.netty.server
 * Date:2016年4月30日下午1:58:28
 * Copyright (c) 2016,  All Rights Reserved.
 *
*/

package com.netty.server;

import java.io.UnsupportedEncodingException;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Constant;

/**
 * ClassName:NettyServerHandler <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason:	 TODO ADD REASON. <br/>
 * Date:     2016年4月30日 下午1:58:28 <br/>
 * @author   i1093108915@yeah.net
 * @version  
 * @since    JDK 1.6
 * @see 	 
 */
public class NettyServerHandler extends ChannelHandlerAdapter {

	  public void channelRead(ChannelHandlerContext ctx, Object msg) {
	    
	    ByteBuf buf = (ByteBuf) msg;
	    
	    String recieved = getMessage(buf);
	    System.out.println("服务器接收到消息：" + recieved);
	    
	    try {
	      ctx.writeAndFlush(getSendByteBuf("APPLE"));
	    } catch (UnsupportedEncodingException e) {
	      e.printStackTrace();
	    }
	  }

	  /*
	   * 从ByteBuf中获取信息 使用UTF-8编码返回
	   */
	  private String getMessage(ByteBuf buf) {

	    byte[] con = new byte[buf.readableBytes()];
	    buf.readBytes(con);
	    try {
	      return new String(con, "UTF8");
	    } catch (UnsupportedEncodingException e) {
	      e.printStackTrace();
	      return null;
	    }
	  }
	  
	  private ByteBuf getSendByteBuf(String message)
	      throws UnsupportedEncodingException {

	    byte[] req = message.getBytes("UTF-8");
	    ByteBuf pingMessage = Unpooled.buffer();
	    pingMessage.writeBytes(req);

	    return pingMessage;
	  }
	}

